<template>
  <div class="c-transaction-process"></div>
</template>

<script>
import { Toast } from "vant";
import { fetchPayWay, calculateAdPrice, createAdOrder } from "./api";
import PayWaySelect from "./components/PayWayPopup/index.js";
import { setOrderCache } from "./utils/index";
import {
  ORDER_PAY_STATUS,
  DEFAULT_PAY_WAY,
  COMMON_ERROR_MSG,
  PAY_WAY,
  PAY_TAB_LIST,
  PAY_WAY_LIST,
  PAY_TYPE_LIST,
  SUB_ORDERS,
} from "./utils/constants";
import { isKSMiniProgram, enableAppPayment, isMiniEnv } from "./utils/checkEnv";
import { producePayParams } from "./parameter/pay-params";
import { getPaymentByType } from "./pay/index";
import { PayBackHandler } from "./strategy/pay-back-handler";
import CopyPasswordDialog from "./components/CopyPassword/index.js";

export default {
  name: "CAdPay",
  props: {
    // 商品信息
    goodsInfo: {
      type: Object,
      default: () => ({
        spu_id: "i_6555ceb5e4b04c100fc6ad76",
        sku_id: "SKU_ITX_7001222942161HBxIY89",
      }),
    },

    // 支付 成功/失败 跳转地址
    jumpData: {
      type: Object,
      default: () => ({
        paySuccessUrl: "",
        payFailUrl: "",
        redirectUrl: "",
      }),
    },
    // 拓展字段
    extendInfo: {
      type: Object,
      default: () => ({
        click_id: "",
        link_user_id: "",
        channel_type: ""
      }),
    },
    promiseResolve: {
      type: Function,
    },
    // promise 对象
    option: {
      type:Function
    }
  },
  data() {
    return {
      valuateData: {}, //批价返回参数
      payWayInfo: {}, // 支付方式信息
      payResult: {}, //下单接口返回
      payWay: 6, // 选择的支付方式
      // jumpData: {
      //   paySuccessUrl: this.jumpDataCustom?.paySuccessUrl,
      //   payFailUrl: this.jumpDataCustom?.payFailUrl,
      //   redirectUrl: this.jumpDataCustom?.redirectUrl,
      // },
    };
  },
  computed: {
    totalPrice() {
      const price = this.valuateData?.price_info?.final_price || 0;
      return (price / 100).toFixed(2);
    },
    ratePrice() {
      const priceInfo = this.valuateData?.price_info || {};
      const { final_price } = priceInfo;
      return final_price >= 0 ? (final_price / 100).toFixed(2) : "--.--";
    },
    priceInt() {
      return this.ratePrice.slice(0, -3);
    },
    priceFloat() {
      return (this.ratePrice >= 0 && this.ratePrice.slice(-3)) || "";
    },
    finalPrice() {
      return this.priceInt + this.priceFloat;
    },
  },
  // watch:
  methods: {
    // 初始化数据
    async initData() {
      // 0：初始值 1：支付方式选择弹框显示 2：支付方式选择弹框关闭
      let showSelectPayWay = 0;

      this.valuateData = await this.getCalculatePrice();
      this.payWayInfo = await this.getPayWay();
      this.payWayInfo.hua_bei_installment_select = [];
      this.payWayInfo.list = this.payWayInfo?.list.filter(
        (res) => res.pay_way != 14
      );
       console.log('888999');
      // 外部 决定是否往下执行
      if (this.option) {
        await this.option()
      }
      console.log('88888');
      // ----- 支付方式选择 -----
      // 默认支付方式
      this.payWay = DEFAULT_PAY_WAY[0].pay_way;
      // 花呗支付信息
      let InstallmentInfo = {};

      let payWayList = this.payWayInfo?.list || [];
        // return
      // 多种支付方式
      if (payWayList.length > 1) {
        // 查找默认支付方式
        for (const ways_index in payWayList) {
          if (payWayList[ways_index]?.is_default == 1) {
            this.payWay = payWayList[ways_index].pay_way;
          }
        }

        this.payWaySelectInstance = new PayWaySelect(
          this.payWayInfo.list,
          [],
          this.totalPrice,
          this.payWay
        );
        InstallmentInfo = await this.payWaySelectInstance.perform();
        const { way, isClose } = InstallmentInfo;
        this.payWay = way;
        // 是否是手动关闭支付方式选择弹框
        if (isClose === 1) {
          showSelectPayWay = 2;
        }
      } else if (payWayList.length === 1) {
        this.payWay = payWayList[0].pay_way;
      }

      // 如果是手动关闭 || 非微信支付，当页进行支付，微信支付，则返回数据，业务侧跳空白页进行下单支付
      if (showSelectPayWay === 2 || this.payWay === 6) {
        this.promiseResolve({
          token: this.valuateData?.token,
          payWay: this.payWay,
          showSelectPayWay,
        });
        return;
      }

      // 下单
      await this.buy();
    },
    // 批价
    getCalculatePrice() {
      const { spu_id, sku_id } = this.goodsInfo;
      const { link_user_id, from_ads ,channel_type, isTourist } = this.extendInfo
      const params = {
        identity_info: {
          identity_type: -1,
        },
        goods_list: [
          {
            spu_id,
            sku_id,
            buy_num: 1,
          },
        ],
        coupon_info: {
          is_selected: true,
          selected_coupons: [],
        },
        trade_type: 1,
        channel_type,
        from_ads
      };
      return calculateAdPrice(params,link_user_id, isTourist);
    },
    // 获取支付方式
    getPayWay() {
      const { token } = this.valuateData;
      // only_wechat_payment 购课-加微模板的落地页只让使用微信支付
      // isTourist 无用户下单
      const { link_user_id, isTourist, only_wechat_payment } = this.extendInfo
      const params = {
        goods_list: [
          {
            spu_id: this.goodsInfo?.spu_id,
            sku_id: this.goodsInfo?.sku_id,
          },
        ],
        is_team_buy: false,
        team_buy_id: "",
        token,
        only_wechat_payment
      };
      return fetchPayWay(params,link_user_id, isTourist);
    },
    // 下单
    buy(data = {}) {
      const { token, payWay } = data;
      const { spu_id, sku_id } = this.goodsInfo;
      const { common_auth_code, click_id, link_user_id ,channel_type, ad_page_id,scrm_link_id, scrm_clue_id, from_ads, isTourist, information_source_id} = this.extendInfo;
      const buyParams = {
        identity_info: {
          identity_type: -1,
        },
        goods_list: [
          {
            spu_id,
            sku_id,
            buy_num: 1,
          },
        ],
        pay_way: payWay || this.payWay,
        token: token || this.valuateData?.token,
        redirect_url: this.jumpData.redirectUrl || "",
        channel_type,
        extend_object_info: {
          channel_info: {
            link_user_id:link_user_id ? link_user_id : '',
            click_id,
            ad_page_id,
            scrm_link_id,
            scrm_clue_id,
            channel_type 
          },
          info_collect_object_info: information_source_id ? { information_source_id: information_source_id.toString() }: undefined
        },
        from_ads
      };

      buyParams.common_auth_code = isTourist ? common_auth_code : undefined;

      return createAdOrder(buyParams,link_user_id, isTourist)
        .then((data) => {
          this.payResult = data;

          const orderId = data.order_id;
          const subOrders = JSON.stringify(data.order_id_list);
          sessionStorage.setItem(SUB_ORDERS, subOrders);

          // 设置默认支付成功、失败跳转地址
          if (!this.jumpData.paySuccessUrl) {
            this.jumpData.paySuccessUrl = `/v1/goods/pay_complete?order_id=${orderId}`;
          }
          if (!this.jumpData.payFailUrl) {
            this.jumpData.payFailUrl = `/v1/usercenter/order/order_details?order_id=${orderId}`;
          }

          // 0元单
          if (data.order_pay_status === ORDER_PAY_STATUS.PAID) {
          } else {
            this.doPay(data,link_user_id, isTourist);
          }
        })
        .catch((err) => {
          Toast({
            message: err?.msg || COMMON_ERROR_MSG,
            duration: 1000,
          });
        });
    },
    // 支付
    doPay(data,link_user_id, isTourist) {
      // 确定支付方式
      const { need_jump: needJump, pay_config: payConfig } = data;
      const { pay_way, pay_type, pay_tab } = payConfig;
      const order = {...data,link_user_id,isTourist}
      const payType = this.getCurrentPayWayName(
        pay_way,
        pay_type,
        pay_tab,
        needJump
      );

      // 组装对应参数
      const payInfoObj = producePayParams(
        payType,
        data,
        this.jumpData,
        "",
        this.ratePrice,
        this.goodsInfo?.spu_id,
        false
      );
      console.log('doPay',order);
      //缓存数据
      const { paySuccessUrl, payFailUrl } = this.jumpData;
      if (payType === PAY_WAY.WxH5Pay || payType === PAY_WAY.AliPay || payType === PAY_WAY.WxJSAPIPay) {
        setOrderCache(paySuccessUrl, payFailUrl, order);
      }

      //具体支付策略
      let payStrategy;

      payStrategy = getPaymentByType(payType);

      // 实施对应支付策略
      payStrategy
        .pay(payInfoObj)
        .then(() => {
          switch (payType) {
            case PAY_WAY.AliPayCommand:
              this.handleAliPay();
              break;
            case PAY_WAY.WxJSAPIPay:
              this.handlePayBack(order,'success');
              break;
            case PAY_WAY.AliPay:
            case PAY_WAY.AliHuabeiPay:
            case PAY_WAY.H5BlankPay:
            case PAY_WAY.WxH5Pay:
              break;
            default:
              return Promise.reject({
                errMsg: "未知支付类型",
                info: {
                  pay_way,
                  pay_type,
                  pay_tab,
                  needJump,
                  payType,
                },
              });
          }
        })
        .catch((err) => {
          this.handlePayBack(order,'fail');
        });
    },
    getCurrentPayWayName(payWay, payType, payTab, needJump) {
      //快手小程序
      if (isKSMiniProgram) {
        return PAY_WAY.KSMiniProgramPay;
      }
      //店铺小程序、鹅圈子小程序、独立圈子小程序、视频号小程序、视频号分销小程序支付
      if (isMiniEnv()) {
        return PAY_WAY.MpBlankPay;
      }
      //吱口令,优先级高，有同时花呗分期、吱口令的情况
      if (payTab === PAY_TAB_LIST.ZFB_ZKL) {
        return PAY_WAY.AliPayCommand;
      }
      //支付宝支付
      if (payWay === PAY_WAY_LIST.ALI_PAY) {
        return PAY_WAY.AliPay;
      }
      //花呗支付
      if (payWay === PAY_WAY_LIST.ALI_HUABEI_PAY) {
        return PAY_WAY.AliHuabeiPay;
      }
      if (
        (payWay === PAY_WAY_LIST.WEIXIN_PAYMENT ||
          payWay === PAY_WAY_LIST.WECHAT_PAY) &&
        payType === PAY_TYPE_LIST.H5 &&
        needJump != 1
      ) {
        return PAY_WAY.WxJSAPIPay;
      }
      if (
        (payWay === PAY_WAY_LIST.WEIXIN_PAYMENT ||
          payWay === PAY_WAY_LIST.WECHAT_PAY) &&
        payType === PAY_TYPE_LIST.APP_H5
      ) {
        return PAY_WAY.WxH5Pay;
      }
      // 印象虚拟币支付
      if (payWay === PAY_WAY_LIST.YX_VIRSUAL_PAY && enableAppPayment) {
        return PAY_WAY.VirtualPay;
      }
      // 跳空白页支付
      if (needJump == 1) {
        return PAY_WAY.H5BlankPay;
      }
      return PAY_WAY.WxJSAPIPay;
    },
    handlePayBack(order,status) {
      const { paySuccessUrl, payFailUrl } = this.jumpData;
      new PayBackHandler(paySuccessUrl, payFailUrl, order, status).perform();
    },
    handleAliPay() {
      const payConfig = {
        ...this.payResult?.pay_config,
        order_id: this.payResult?.order_id,
        trade_id: this.payResult?.trade_id,
        ...this.jumpData,
       link_user_id:this.extendInfo?.link_user_id
      };
      new CopyPasswordDialog(payConfig, this.finalPrice).perform();
    },
  },
};
</script>

<style lang="scss" scoped>
.c-transaction-process {
  // font-size: 32px;
}
</style>
